package ui.util;

import cerebrum.common.EmptyChecker;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.io.IOException;
import java.rmi.ServerException;

/**
 * <p>
 * 所有窗口的父类
 */
public abstract class Window extends Stage {
    public Parent root;
    private double xOffset;
    private double yOffset;

    /**
     * 设置图标方法
     */
    public void setIcon() {
        getIcons().add(new Image("/fxml/css/images/b1.png"));

    }

    /**
     * 窗口移动方法
     */
    public void move() {
        root.setOnMousePressed(event -> {
            xOffset = getX() - event.getScreenX();
            yOffset = getY() - event.getScreenY();
            getRoot().setCursor(Cursor.CLOSED_HAND);

        });
        root.setOnMouseDragged(event -> {

            setX(event.getScreenX() + xOffset);
            setY(event.getScreenY() + yOffset);


        });
        root.setOnMouseReleased(event -> {
            root.setCursor(Cursor.DEFAULT);

        });
    }

    /**
     * 获取root
     *
     * @return
     */
    public Parent getRoot(){
        return root;
    }

    /**
     * 选择界面元素
     *
     * @param id 元素id
     * @return
     */
    public Object $(String id) {
        return root.lookup("#" + id);
    }

    /**
     * 鼠标样式改变
     * @param node 节点名称
     */
    public void setCursor(Node node) {
        node.addEventHandler(MouseEvent.MOUSE_ENTERED, e -> node.setCursor(Cursor.HAND));
    }

    public void removeNode(Pane node, String id) {
        ObservableList<Node> ol = FXCollections.observableArrayList(node.getChildren());
        int oldSize = ol.size();
        for (int i = 0; i < ol.size(); i++) {
            Node no = ol.get(i);
            if (EmptyChecker.notEmpty(no.getId())&&id.equals(no.getId())){
                ol.remove(i);
                break;
           }
        }
        if (ol.size() == oldSize){
            throw new RuntimeException("not found id \""+id+"\" in node");
        }
        node.getChildren().setAll(ol);
    }

}